package spring.webapp.anmeldesystem.controller;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import spring.webapp.anmeldesystem.entity.User;
import spring.webapp.anmeldesystem.service.AdminService;

/**
 * Controller for admin page.
 * 
 * @author Songhua Cui
 * 
 */
@Controller
@RequestMapping
public class adminController {

	@Autowired
	private AdminService adminService;

	/**
	 * Add new user to system.
	 * 
	 * @param email
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/addUser", method = RequestMethod.POST)
	public @ResponseBody
	String getUser(@RequestParam(value = "role", required = true) String role,
			@RequestParam(value = "name", required = false) String name,
			@RequestParam(value = "faculity", required = false) String faculity) {
		String message = "";
		if (!StringUtils.isBlank(name)) {
			message = adminService.addNewUser(role, name, faculity);
		} else {
			message = "Bitte Input-Daten korrigieren! Benutzername darf nicht leer sein.";
		}

		return message;
	}

	/**
	 * Get user to manage.
	 * 
	 * @param email
	 */
	@RequestMapping(value = "/getUser", method = RequestMethod.POST)
	public @ResponseBody
	User getUser(@RequestParam(value = "email", required = true) String email) {
		List<User> users = adminService.getUserByEmail(email);
		User user = null;
		if (users != null && !users.isEmpty()) {
			user = users.get(0);
		}
		return user;
	}

	/**
	 * Method resets the password for given user.
	 * 
	 * @param model
	 * @param request
	 * @param dateiId
	 * @return
	 */
	@RequestMapping(value = "/resetPassword")
	public @ResponseBody
	String resetPassword(
			@RequestParam(value = "email", required = true) String email,
			@RequestParam(value = "name", required = false) String name) {
		adminService.resetPassword(email);
		return "Kennword von User " + name + " wurde zurückgesetzt.";
	}

	/**
	 * Method deletes selected user.
	 * 
	 * @return message should be shown in client.
	 */
	@RequestMapping(value = "/deleteUser")
	public @ResponseBody
	String delete(@RequestParam(value = "email", required = true) String email,
			@RequestParam(value = "name", required = false) String name) {
		adminService.deleteUser(email);
		return "User " + name + " wurde aus System entfernt.";
	}
}
